import React, { useCallback, useEffect, useReducer } from 'react';
import PageHeader from '@/components/page/PageHeader';
import { Table, Button, Modal, message } from 'antd';
import DataEdit from '@/components/base/DataEdit';
import { fetch } from '@/services/commCRUD';
import { ProFormMoney, ProFormText } from '@ant-design/pro-form';
import { AddTzje } from '@/services/commCRUD';
import { useModel } from 'umi';
import { format } from '@/utils/datetime';
import _ from 'lodash';

const daoName = 'BMTZJE';
type StateField = {
  selDate?: string;
  listData?: Record<string, any>[];
  load?: boolean;
};
const BMTZJE: React.FC = () => {
  const { user } = useModel('@@initialState', (ret) => {
    return {
      user: ret.initialState?.user,
    };
  });
  const [state, dispatch] = useReducer(
    (prevState: StateField, newState: StateField) => {
      return { ...prevState, ...newState };
    },
    {
      selDate: format(new Date(), 'yyyyMM'),
      listData: [],
      load: false,
    },
  );
  const changeHandle1 = (val: any, emno: string) => {
    const idx = state.listData?.findIndex((r) => r.EMNO === emno);
    if (idx && idx < 0) {
      return;
    }
    const newld = [...state.listData!];
    newld[idx!].YJJXTZJE = Number(val);
    dispatch({ listData: newld });
  };
  const renderYJJXTZJE = (rowData: any) => {
    const value = rowData.YJJXTZJE;
    return (
      <div style={{ marginTop: -1, marginBottom: -25 }}>
        <ProFormMoney
          name=""
          min={-999999}
          max={999999}
          fieldProps={{
            value: value,
            onChange: (val) => changeHandle1(val, rowData.EMNO),
          }}
        />
      </div>
    );
  };
  const changeHandle2 = (val: any, emno: string) => {
    const idx = state.listData?.findIndex((r) => r.EMNO === emno);
    if (idx && idx < 0) {
      return;
    }
    const newld = [...state.listData!];
    newld[idx!].YWJXTZJE = Number(val);
    dispatch({ listData: newld });
  };
  const renderYWJXTZJE = (rowData: any) => {
    return (
      <div style={{ marginTop: -1, marginBottom: -25 }}>
        <ProFormMoney
          name=""
          min={-999999}
          max={999999}
          fieldProps={{
            value: rowData.YWJXTZJE,
            onChange: (val) => changeHandle2(val, rowData.EMNO),
          }}
        />
      </div>
    );
  };
  const changeHandle3 = (val: any, emno: string) => {
    const idx = state.listData?.findIndex((r) => r.EMNO === emno);
    if (idx && idx < 0) {
      return;
    }
    const newld = [...state.listData!];
    newld[idx!].TZYY = String(val);
    dispatch({ listData: newld });
  };
  const renderTZYY = (rowData: any) => {
    return (
      <div style={{ marginTop: -1, marginBottom: -25 }}>
        <ProFormText
          name="TZYY"
          fieldProps={{
            value: rowData.TZYY,
            maxLength: 200,
            onChange: (e) => changeHandle3(e.target.value, rowData.EMNO),
          }}
        />
      </div>
    );
  };
  const columns: API.Column[] = [
    {
      title: '部门',
      width: 110,
      sorter: true,
      key: 'DPNM',
      dataIndex: 'DPNM',
      dispaly: true,
      filter: true,
      export: true,
    },
    {
      title: '员工工号',
      width: 110,
      sorter: true,
      dataIndex: 'EMNO',
      key: 'EMNO',
      dispaly: true,
      filter: true,
      export: true,
    },
    {
      title: '员工姓名',
      width: 110,
      sorter: true,
      dataIndex: 'EMNM',
      key: 'EMNM',
      dispaly: true,
      filter: true,
      export: true,
    },
    {
      title: '营业室柜面人员',
      width: 110,
      sorter: true,
      dataIndex: 'ISYYS',
      key: 'ISYYS',
      render: (isyys) => (isyys === 1 ? '是' : ''),
      dispaly: true,
      filter: true,
      export: true,
    },
    {
      title: '业绩绩效（打分调整后）',
      width: 130,
      sorter: true,
      key: 'YJJX',
      dataIndex: 'YJJX',
      dispaly: true,
      filter: true,
      export: true,
    },
    {
      title: '业务绩效（系统值）',
      width: 110,
      sorter: true,
      key: 'YWJX',
      dataIndex: 'YWJX',
      dispaly: true,
      filter: true,
      export: true,
    },
    {
      title: '业绩绩效调整金额',
      width: 110,
      className: 'column-money',
      sorter: true,
      key: 'YJJXTZJE',
      render: (rowData: any) => renderYJJXTZJE(rowData),
      dispaly: true,
      align: 'left',
      filter: true,
      export: true,
    },
    {
      title: '业务绩效调整金额',
      width: 110,
      className: 'column-money',
      sorter: true,
      key: 'YWJXTZJE',
      render: (rowData: any) => renderYWJXTZJE(rowData),
      dispaly: true,
      align: 'left',
      filter: true,
      export: true,
    },
    {
      title: '调整原因(200字以内)',
      width: 210,
      sorter: true,
      className: 'column-text',
      key: 'TZYY',
      render: (rowData: any) => renderTZYY(rowData),
      dispaly: true,
      filter: true,
      align: 'left',
      export: true,
    },
    {
      title: '错误提示',
      width: 130,
      sorter: true,
      key: 'TZJECW',
      dataIndex: 'TZJECW',
      dispaly: true,
      filter: true,
      export: true,
    },
  ];
  const loadData = useCallback(
    (jd_val: string) => {
      dispatch({ load: true });
      const seeks: API.WhereCause[] = [
        {
          WhereItems: [
            {
              FieldName: 'FFJD',
              Operator: '=',
              FieldValues: '' + jd_val,
            },
            {
              FieldName: 'PDID',
              Operator: '=',
              FieldValues: '' + user?.pOrgID,
            },
          ],
          RelationSign: 'AND',
        },
      ];
      const order: API.OrderItem = {
        FieldName: 'EMNO',
        Direction: 'ASC',
      };
      fetch(daoName, 1, 2000, [order], seeks, 0)
        .then(function (data) {
          const ldata = _.isEmpty(data.Objectlist) ? [] : data.Objectlist;
          dispatch({ selDate: jd_val, listData: ldata, load: false });
        })
        .catch(function (ex) {
          dispatch({ load: false });
          console.error('请求', daoName, '错误', ex);
        });
    },
    [user?.pOrgID],
  );
  useEffect(() => {
    loadData(state.selDate!);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  const valuesChange = (row: Record<string, any>) => {
    const dstr = row.FFJD.replace('-', '');
    loadData(dstr);
  };
  const submit = async () => {
    Modal.confirm({
      title: '提示',
      content: `你确认要保存吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        const vals: Record<string, any> = [];
        state.listData!.map((o) => {
          vals.push({
            FFJD: o.FFJD,
            EMNO: o.EMNO,
            DPID: o.DPID,
            PDID: o.PDID,
            YJJXTZJE: o.YJJXTZJE,
            YWJXTZJE: o.YWJXTZJE,
            TZYY: o.TZYY,
            EMNM: o.EMNM,
          });
        });
        AddTzje(vals, state.selDate!)
          .finally(function () {
            loadData(state.selDate!);
          })
          .then(function () {
            message.success('保存成功');
          });
      },
    });
  };
  return (
    <PageHeader>
      <div style={{ marginTop: -8, marginBottom: 5 }}>
        <DataEdit
          showType="inner"
          layout="inline"
          controls={[
            {
              name: 'FFJD',
              dataType: 'date',
              type: 'month',
              label: '选择月份',
              rules: [{ required: true, message: '季度不能为空' }],
              width: 120,
              initValue: state.selDate,
            },
          ]}
          onSumit={submit}
          onValuesChange={(_cvals, vals) => valuesChange(vals)}
          renderButtons={(p) => {
            return [
              <Button type="primary" key="submit" onClick={() => p.form?.submit?.()}>
                保存
              </Button>,
            ];
          }}
        />
      </div>
      <Table
        columns={columns}
        dataSource={state.listData}
        loading={state.load}
        rowKey={(record) => record.ID}
        bordered={true}
        pagination={false}
        size="small"
      />
    </PageHeader>
  );
};

export default BMTZJE;
